package com.bosssoft.boss_exam_web.Controller;


import com.bosssoft.boss_exam_core.enums.business.ExamEnum;
import com.bosssoft.boss_exam_core.enums.business.ExamPaperCheckEnum;
import com.bosssoft.boss_exam_core.exception.QueryDataException;
import com.bosssoft.boss_exam_core.exception.UpdateEntityException;
import com.bosssoft.boss_exam_core.util.json.JsonUtil;
import com.bosssoft.boss_exam_core.util.web.ResponseUtil;
import com.bosssoft.boss_exam_core.validator.Order;
import com.bosssoft.boss_exam_core.validator.Sort;
import com.bosssoft.boss_exam_db.entity.ApplicantExam;
import com.bosssoft.boss_exam_db.entity.ApplicantExamPaper;
import com.bosssoft.boss_exam_db.entity.ExamExamPaper;
import com.bosssoft.boss_exam_db.model.vo.ApplicantExamVO;
import com.bosssoft.boss_exam_db.service.busines.AdminService;
import com.bosssoft.boss_exam_db.service.busines.ApplicantExamPaperService;
import com.bosssoft.boss_exam_db.service.busines.ApplicantExamService;
import com.bosssoft.boss_exam_db.service.busines.ExamExamPaperService;
import com.bosssoft.boss_exam_web.common.annotation.LoginAdmin;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@Validated
@Slf4j
@Api(value="应聘者考试控制器")
public class ApplicantExamController {

    // 引入管理员服务
    @Autowired
    private AdminService adminService;

    //引入应聘者考试服务
    @Autowired
    private ApplicantExamService applicantExamService;

    // 引入应聘者试卷服务
    @Autowired
    private ApplicantExamPaperService applicantExamPaperService;

    // 引入考试-试卷服务
    @Autowired
    private ExamExamPaperService examExamPaperService;

    // 引入事务管理器
    @Autowired
    @Qualifier("transactionManager")
    private PlatformTransactionManager transactionManager;

    @ApiOperation(value="应聘者考试查询", notes="可根据应聘者考试名称查询应聘者考试" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="allowExamFlag", value="是否允许考试的标志", dataType = "Integer", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="page", value="当前页码", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="limit", value="每页显示条数", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="sort", value="排序依据", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="order", value="排序方式", dataType = "String", required=false, dataTypeClass=String.class)
    })
    @GetMapping("/admin/applicantExam/list")
    public Object list(@LoginAdmin String adminId,
                       @RequestParam(defaultValue = "1") Integer allowExamFlag,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if ( adminId == null) {
            return ResponseUtil.unlogin();
        }
        PageInfo<ApplicantExamVO> applicantExamPageInfo = applicantExamService.queryByCondition(allowExamFlag,page, limit, sort, order);
        if(applicantExamPageInfo==null){
            log.error("【业余错误】，查询pageInfo为空");
            throw new QueryDataException();
        }else {
            Map<String, Object> data = new HashMap<>();
            data.put("total", applicantExamPageInfo.getTotal());
            data.put("items", applicantExamPageInfo.getList());
            return ResponseUtil.ok(data);
        }
    }


    @ApiOperation(value="允许/禁止考试", notes="更新应聘者考试状态" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="applicantExam", value="应聘者考试对象json，必须携带应聘者考试ID", dataType = "ApplicantExam", required=true, dataTypeClass= ApplicantExam.class),
    })
    @PostMapping("/admin/applicantExam/update")
    public Object update(@LoginAdmin String  adminId, @RequestBody ApplicantExam applicantExam) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
//       引入编程事务
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
//       设置事务传播行为：required 如有事务加入事务，无事务新建一起事务
//       作用将多个service操作都使用同一个connection事务
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(defaultTransactionDefinition);
        try{
            if (adminId == null) {
                return ResponseUtil.unlogin();
            }
            int recordNum = applicantExamService.updateNotNull(applicantExam);
            //允许考试后吗，给应聘者分配卷子和阅卷官
            // 查询考试对应的试卷
            List<ExamExamPaper> examExamPapers = examExamPaperService.queryExamPaperByExamId(applicantExam.getExamId());
            Boolean isExits= false;
            ApplicantExamPaper tmpApplicantExamPaper =null;
            if(examExamPapers!=null && examExamPapers.size()!=0){
                String examPaperId = examExamPapers.get(0).getExamPaperId();
                List<ApplicantExamPaper> applicantExamPapers = applicantExamPaperService.queryByExamIdAndExamPaperId(applicantExam.getExamId(),examPaperId);
                if(applicantExamPapers!=null && applicantExamPapers.size()!=0){
                    isExits =true;
                    tmpApplicantExamPaper = applicantExamPapers.get(0);
                }
            }
            if(isExits){
                if(tmpApplicantExamPaper!=null){
                    this.applicantExamPaperService.deleteForLogic(tmpApplicantExamPaper);
                }
            }
            if(applicantExam.getAllowExam().equals(ExamEnum.ALLOW_EXAM.getCode())){
                ApplicantExamPaper applicantExamPaper=null;
                // 查询考试对应的试卷
                List<ExamExamPaper> examExamPaperList = examExamPaperService.queryExamPaperByExamId(applicantExam.getExamId());
                if(examExamPaperList!=null && examExamPaperList.size()!=0){
                    applicantExamPaper = new ApplicantExamPaper();
                    // 应聘人ID
                    applicantExamPaper.setApplicantId(applicantExam.getApplicantId());
                    // 考试ID
                    applicantExamPaper.setExamId(applicantExam.getExamId());
                    String examPaperId = examExamPaperList.get(0).getExamPaperId();
                    // 试卷ID
                    applicantExamPaper.setExamPaperId(examPaperId);
                    String adminIdArr = examExamPaperList.get(0).getAdminIdArr();
                    List<String> checkPeopleList = JsonUtil.json2Object(adminIdArr, List.class);
                    int randomIndex = new Random().nextInt(checkPeopleList.size());
                    String selectCheckPeopleId = checkPeopleList.get(randomIndex);
                    // 阅卷官
                    applicantExamPaper.setCheckPeopleId(selectCheckPeopleId);
                    // 是否阅卷
                    applicantExamPaper.setChecked(ExamPaperCheckEnum.NO_CHECK.getCode());
                }
                int result = applicantExamPaperService.saveNotNull(applicantExamPaper);
            }
            if(recordNum!=1){
                log.error("【系统错误】 保存应聘者考试失败");
                throw  new UpdateEntityException();
            }
            // 事务提交
            transactionManager.commit(status);
            return ResponseUtil.ok(recordNum);
        }catch (Exception e){
            transactionManager.rollback(status);
            throw new UpdateEntityException(e);
        }
    }
}
